package com.example.s09_websocket.server;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: zhangming
 * @Date: 2022/4/4 10:41
 */
@ServerEndpoint("/chat-room/{username}")
@Component
public class ChatServer {
    // ConcurrentHashMap 多线程时使用的Map接口实现类

    // 保存所有连接信息
    public static final Map<String, Session> ONLINE_USER_SESSIONS = new ConcurrentHashMap<>();

    // 保存所有在线用户的Session
    @OnOpen
    public void openSession(@PathParam("username") String username, Session session) {
        ONLINE_USER_SESSIONS.put(username, session);

        String message = "欢迎用户[" + username + "] 来到聊天室！";
        System.out.println(message);
//        logger.info("用户登录："+message);
        sendMessageAll(message);
    }


    @OnMessage
    public void onMessage(@PathParam("username") String username, String message) {
//        logger.info("发送消息："+message);
        System.out.println(username + ":" + message);
        sendMessageAll("用户[" + username + "] : " + message);
    }

    // 关闭连接
    @OnClose
    public void onClose(@PathParam("username") String username, Session session) {
        //当前的Session 移除
        ONLINE_USER_SESSIONS.remove(username);
        //并且通知其他人当前用户已经离开聊天室了
        sendMessageAll("用户[" + username + "] 已经离开聊天室了！");
        try {
            session.close();
        } catch (IOException e) {
//            logger.error("onClose error", e);
        }
    }

    // 发送消息
    public static void sendMessageAll(String message) {
        ONLINE_USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, message));
    }


    public static void sendMessage(Session session, String message) {
        if (session == null) {
            return;
        }
        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic == null) {
            return;
        }
        try {
            basic.sendText(message);
        } catch (IOException e) {
//            logger.error("sendMessage error", e);
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        try {
            session.close();
        } catch (IOException e) {
//            logger.error("onError excepiton", e);
        }
//        logger.info("Throwable msg " + throwable.getMessage());
    }

}
